﻿using Newtonsoft.Json;
using QWManage.API.AccessToken;
using QWManage.DAL;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.IO;
using System.Windows.Forms;

namespace QWManage
{
    public partial class FrmSetting : Form
    {
        public FrmSetting()
        {
            InitializeComponent();
        }

        private void FrmSetting_Load(object sender, EventArgs e)
        {
            chbDaily.CheckedChanged += ComboBoxes_CheckedChanged;
            cmbGroups.CheckedChanged += ComboBoxes_CheckedChanged;
            AppConfigInfo appConfigInfo = AppCofingMgr.Get();
            initialize(appConfigInfo);
        }

        private void initialize(AppConfigInfo appConfigInfo)
        {
            chbYiYeMatched.Checked = appConfigInfo.YiYeMatched;
            txtCorpName.Text = appConfigInfo.CorpName;
            txtCorpid.Text = appConfigInfo.Corpid;
            txtCorpsecretA.Text = appConfigInfo.CorpsecretA;
            txtCorpsecretB.Text = appConfigInfo.CorpsecretB;

            txtDataSource.Text = appConfigInfo.DataSource;
            txtInitialCatalog.Text = appConfigInfo.InitialCatalog;
            txtUserID.Text = appConfigInfo.UserID;
            txtPassword.Text = appConfigInfo.Password;
            txtConnectTimeout.Text = appConfigInfo.ConnectTimeout.ToString();

            #region 定时
            cmbHour.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbHourStart.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbHourEnd.DropDownStyle = ComboBoxStyle.DropDownList;
            for (int hour = 0; hour <= 23; hour++)
            {
                cmbHour.Items.Add(hour.ToString("00时"));
                cmbHourStart.Items.Add(hour.ToString("00时"));
                cmbHourEnd.Items.Add(hour.ToString("00时"));
            }
            cmbMinute.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbMinuteStart.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbMinuteEnd.DropDownStyle = ComboBoxStyle.DropDownList;
            for (int minute = 0; minute <= 59; minute++)
            {
                cmbMinute.Items.Add(minute.ToString("00分"));
                cmbMinuteStart.Items.Add(minute.ToString("00分"));
                cmbMinuteEnd.Items.Add(minute.ToString("00分"));
            }

            AppConfigInfo appConfig = AppCofingMgr.Get();
            chbDaily.Checked = appConfig.Daily;
            cmbGroups.Checked = appConfig.Groups;

            cmbHour.Enabled = chbDaily.Checked;
            cmbMinute.Enabled = chbDaily.Checked;

            cmbHourStart.Enabled = cmbGroups.Checked;
            cmbMinuteStart.Enabled = cmbGroups.Checked;
            cmbHourEnd.Enabled = cmbGroups.Checked;
            cmbMinuteEnd.Enabled = cmbGroups.Checked;

            cmbHour.Text = appConfig.Hour.ToString("00时");
            cmbHourStart.Text = appConfig.HourStart.ToString("00时");
            cmbHourEnd.Text = appConfig.HourEnd.ToString("00时");


            cmbMinute.Text = appConfig.Minute.ToString("00分");
            cmbMinuteStart.Text = appConfig.MinuteStart.ToString("00分");
            cmbMinuteEnd.Text = appConfig.MinuteEnd.ToString("00分");
            #endregion
        }
        private void ComboBoxes_CheckedChanged(object sender, EventArgs e)
        {
            cmbHour.Enabled = chbDaily.Checked;
            cmbMinute.Enabled = chbDaily.Checked;

            cmbHourStart.Enabled = cmbGroups.Checked;
            cmbMinuteStart.Enabled = cmbGroups.Checked;
            cmbHourEnd.Enabled = cmbGroups.Checked;
            cmbMinuteEnd.Enabled = cmbGroups.Checked;
        }

        private bool checkTextBoxEmpty(string name, TextBox textBox)
        {
            if (string.IsNullOrEmpty(textBox.Text.Trim()))
            {
                Common.MessageBoxWarning($"\"{name}\"不能为空，请输入数据。");
                return false;
            }
            return true;
        }

        private AppConfigInfo GetAppConfigInfo()
        {

            if (!checkTextBoxEmpty("CorpName", txtCorpName)) return null;
            if (!checkTextBoxEmpty("Corpid", txtCorpid)) return null;
            if (!checkTextBoxEmpty("通讯录 Corpsecret", txtCorpsecretB)) return null;
            if (!checkTextBoxEmpty("客户联系 Corpsecret", txtCorpsecretA)) return null;

            if (!checkTextBoxEmpty("DataSource", txtDataSource)) return null;
            if (!checkTextBoxEmpty("InitialCatalog", txtInitialCatalog)) return null;
            if (!checkTextBoxEmpty("UserID", txtUserID)) return null;
            if (!checkTextBoxEmpty("Password", txtPassword)) return null;

            int timeout;
            if (!int.TryParse(txtConnectTimeout.Text.Trim(), out timeout) || timeout <= 0 || timeout > 1000000)
            {
                Common.MessageBoxWarning("无效的超时时间：" + txtConnectTimeout.Text.Trim());
                return null;
            }

            AppConfigInfo appConfigInfo = new AppConfigInfo()
            {
                YiYeMatched = chbYiYeMatched.Checked,
                CorpName = txtCorpName.Text.Trim(),
                Corpid = txtCorpid.Text.Trim(),
                CorpsecretA = txtCorpsecretA.Text.Trim(),
                CorpsecretB = txtCorpsecretB.Text.Trim(),

                DataSource = txtDataSource.Text.Trim(),
                InitialCatalog = txtInitialCatalog.Text.Trim(),
                UserID = txtUserID.Text.Trim(),
                Password = txtPassword.Text.Trim(),
                ConnectTimeout = timeout
            };

            string fnA = Path.Combine(Application.StartupPath, "tokenA.txt");
            string fnB = Path.Combine(Application.StartupPath, "tokenB.txt");
            if (File.Exists(fnA)) File.Delete(fnA);
            if (File.Exists(fnB)) File.Delete(fnB);


            #region 定时

            appConfigInfo.Daily = chbDaily.Checked;
            appConfigInfo.Hour = Convert.ToInt32(cmbHour.Text.TrimEnd('时'));
            appConfigInfo.Minute = Convert.ToInt32(cmbMinute.Text.TrimEnd('分'));

            appConfigInfo.Groups = cmbGroups.Checked;
            appConfigInfo.HourStart = Convert.ToInt32(cmbHourStart.Text.TrimEnd('时'));
            appConfigInfo.MinuteStart = Convert.ToInt32(cmbMinuteStart.Text.TrimEnd('分'));

            appConfigInfo.HourEnd = Convert.ToInt32(cmbHourEnd.Text.TrimEnd('时'));
            appConfigInfo.MinuteEnd = Convert.ToInt32(cmbMinuteEnd.Text.TrimEnd('分'));

            if (appConfigInfo.Groups)
            {
                int min = Convert.ToInt32(appConfigInfo.HourStart.ToString("00") + appConfigInfo.MinuteStart.ToString("00"));
                int max = Convert.ToInt32(appConfigInfo.HourEnd.ToString("00") + appConfigInfo.MinuteEnd.ToString("00"));
                if (min >= max)
                {
                    Common.MessageBoxWarning("起始时间要小于结束时间");
                    return null;
                }
            }
            return appConfigInfo;
            #endregion
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            AppConfigInfo appConfigInfo = GetAppConfigInfo();
            if (appConfigInfo != null)
            {
                AppCofingMgr.Set(appConfigInfo);
                DialogResult = DialogResult.OK;
            }
        }

        private void btnTestB_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;

                string message = string.Empty;
                bool result = TokenTest.Check(txtCorpid.Text.Trim(), txtCorpsecretB.Text.Trim(), ref message);
                if (result)
                    Common.MessageBoxInformation("获取 通讯录 Token成功。");
                else
                    Common.MessageBoxWarning("获取 通讯录 Token失败：\r\n" + message);
            }
            catch (Exception ex)
            {
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnTestA_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                string message = string.Empty;
                bool result = TokenTest.Check(txtCorpid.Text.Trim(), txtCorpsecretA.Text.Trim(), ref message);
                if (result)
                    Common.MessageBoxInformation("获取 客户联系 Token 成功。");
                else
                    Common.MessageBoxWarning("获取 客户联系 Token 失败：\r\n" + message);
            }
            catch (Exception ex)
            {
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnDBConnect_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                int timeout;
                if (!int.TryParse(txtConnectTimeout.Text.Trim(), out timeout) || timeout <= 0 || timeout > 1000000)
                {
                    Common.MessageBoxWarning("无效的超时时间：" + txtConnectTimeout.Text.Trim());
                    return;
                }
                string message = string.Empty;
                bool result = SqlDAL.ConnectionTest(
                    txtDataSource.Text.Trim(),
                    txtInitialCatalog.Text.Trim(),
                    txtUserID.Text.Trim(),
                    txtPassword.Text.Trim(),
                    ref message);
                if (result)
                    Common.MessageBoxInformation("数据连接测试成功。");
                else
                    Common.MessageBoxWarning("数据连接测试失败：\r\n" + message);

            }
            catch (Exception ex)
            {
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            string cfg_path = Path.Combine(Application.StartupPath, "CFGS");
            if (!Directory.Exists(cfg_path))
            {
                Directory.CreateDirectory(cfg_path);
            }
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "配制文件(*.cfg)|*.cfg";
            dlg.InitialDirectory = cfg_path;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string json = File.ReadAllText(dlg.FileName, System.Text.Encoding.UTF8);
                AppConfigInfo appConfigInfo = JsonConvert.DeserializeObject<AppConfigInfo>(json);
                initialize(appConfigInfo);
            }
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            AppConfigInfo appConfigInfo = GetAppConfigInfo();
            if (appConfigInfo != null)
            {
                string cfg_path = Path.Combine(Application.StartupPath, "CFGS");
                if (!Directory.Exists(cfg_path))
                {
                    Directory.CreateDirectory(cfg_path);
                }
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "配制文件(*.cfg)|*.cfg";
                dlg.InitialDirectory = cfg_path;
                dlg.DefaultExt = ".cfg";
                dlg.FileName = appConfigInfo.CorpName;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string json = JsonConvert.SerializeObject(appConfigInfo);
                    File.WriteAllText(dlg.FileName, json, System.Text.Encoding.UTF8);
                }
            }
        }
    }
}
